
app.directive('mcSummary', ["$window", function($window){
	return {
		restrict: "E",
		replace: true,
		templateUrl: "views/tmpl_summary.html",
		link: function(scope, element, attrs){

		}
	}
}]);

app.directive('mcHeader', ["$window", function($window){
	return {
		restrict: "E",
		replace: true,
		templateUrl: "views/tmpl_header.html",
		link: function(scope, element, attrs){

		}
	}
}]);

app.directive('mcMenu', function($window){
	return {
		restrict: "E",
		replace: true,
		templateUrl: "views/tmpl_menu.html",
		link: function(scope, element, attrs){

		}
	}
});

app.directive('mcFooter', function(){
	return {
		restrict: "E",
		replace: true,
		templateUrl: "views/tmpl_footer.html"
	}
});
//------------------------------------------------------ for doctor list
app.directive('doctorList', function(snsService){
	return {
		restrict: "E",
		replace: true,
		templateUrl: "views/doctor/doctor_list_tmpl.html",
		scope : {
			topics : '=topics',
			inclub: '=inclub'
		},
		link: function(scope, element, attrs){

		}
	}
});

// scrollable topic list
app.directive('mcTopicList', function(snsService){
	return {
		restrict: "E",
		replace: true,
		templateUrl: "views/tmpl_topic_list.html",
		scope : {
            topics : '=topics',
            inclub: '=inclub'
        },
		link: function(scope, element, attrs){

		}
	}
});


app.directive('mcTopic', function(snsService){
	return {
		restrict: "E",
		replace: true,
		templateUrl: "views/tmpl_topic.html",
		scope : {
            topic : '=topic',
            inclub: '=inclub'
        },
		link: function(scope, element, attrs){
		}
	}
});


app.directive('mcTopicDetail', function($modal,$rootScope,snsService){
	return {
		restrict: "E",
		replace: true,
		templateUrl: "views/tmpl_topic_deail.html",
		scope : {
            topic : '=topic',
            inclub: '=inclub'
        },
		link: function(scope, element, attrs){
			var article = element[0].querySelector(".topic-article");
			scope.hasToggle = false;
			scope.isOwner = false;
			if($rootScope.userProfile){
				if($rootScope.userProfile.userId == scope.topic.user.userId){
					scope.isOwner = true;
				}
			}
			setTimeout(function(){
				scope.isColapsed = article.offsetHeight>120;
				scope.hasToggle = scope.isColapsed;
				scope.$apply();
			}, 1);
			scope.toggleColapse = function(){
				if(scope.hasToggle){
					scope.isColapsed = !scope.isColapsed;
				}
				return;
			};
			scope.removeTopic = function(option){
				//option = {type:'topic', snsTopicId:1}
				option.scope = scope;
				var modalInstance = $modal.open({
					templateUrl: 'views/tmpl_modal_delete_confirm.html',
					controller: ModalConfirmDeleteCtrl,
					size: 'sm',
					resolve: {
						removeOption: function () {							
							return option;
						}
					}
				});
				
			};
			scope.addReply = function(snsTopicId){
				scope.$parent.showReplyComment =true;
				scope.$parent.currentTopicId = snsTopicId;
				var modalInstance = $modal.open({
					templateUrl: 'views/tmpl_modal_addreply.html',
					controller: ModalAddReplyCtrl,
					size: 'md',
					resolve: {
						replyObj: function () {							
							return {snsTopicId:snsTopicId, scope:scope};
						}
					}
				});

			};			
			scope.voteTopic = function(snsTopicId){
				var params = {
					"snsTopicId": snsTopicId,
					"isSupport": true
				}
				snsService.voteTopic(params).then(function(data){
				
					if(data.status ==0){
						
						if(scope.topic.snsTopicId == snsTopicId){
							scope.topic.isVotedByLoginUser = true;
							scope.topic.supportCount++;
						}
						
					}
					return;
					// don't need popup dialog now
					if(data.friendlyMessage){
						var modalInstance = $modal.open({
							templateUrl: 'views/tmpl_modal_alert.html',
							controller: ModalAlertCtrl,
							size: 'sm',
							resolve: {
								alertObj: function () {							
									return {message:data.friendlyMessage};
								}
							}
						});
					}

					
				});
			};
			scope.$on("REFRESH_TOPIC_REPLIES", function(event, data){
				var paramReply = {
					"snsTopicId":data,
					"page" : 1,
					"countPerPage" : 3,
					"sortOption": 1
				}
				snsService.getReplies(paramReply).then(function(replydata){
					if(replydata.status ==0){	
						scope.topic.replyCount = replydata.data.replies.length;			
						scope.topic.partReplies = replydata.data.replies;
					}
				})
			});
			scope.showImage = function(index){
				//console.log(scope.topic.images[index]);
				Log.log("===== show image slider")
				$rootScope.$emit("SHOW_IMAGE_SLIDER_EVENT", {index:index, images:scope.topic.images});
			};
		}
	}
});

app.directive('mcPhoto', function($modal,$rootScope,snsService){
	return {
		restrict: "E",
		replace: true,
		templateUrl: "views/tmpl_phots.html",
		scope : {
			photo : '=photo'
		}

	}
});

app.directive('mcTopicReplies', function($rootScope, $modal, snsService){
	return {
		restrict: "E",
		replace: true,
		templateUrl: "views/tmpl_topic_replies.html",
		scope : {
            topic : '=topic',
            inclub: '=inclub'
        },
		link: function(scope, element, attrs){
			var currentPage = 1,
			countPerPage = 10,
			startAt = 1,
			endAt = 3;
			scope.ownerId = $rootScope.userProfile? $rootScope.userProfile.userId : -1;
			scope.hasMore = scope.topic.replyCount>endAt?true:false;
			scope.removeReply = function(snsReplyId){
				var modalInstance = $modal.open({
					templateUrl: 'views/tmpl_modal_delete_confirm.html',
					controller: ModalConfirmDeleteCtrl,
					size: 'sm',
					resolve: {
						removeOption: function () {							
							return {type:"reply", snsReplyId: snsReplyId, snsTopicId:scope.topic.snsTopicId,scope:scope.$parent.$parent};
						}
					}
				});
			};
			scope.showMoreReplies = function(snsTopicId){
				currentPage++;
				if((currentPage-1)*countPerPage+startAt > scope.topic.replyCount){
					endAt = scope.topic.replyCount;
				}else{
					endAt = (currentPage-1)*countPerPage+startAt;
				}
				scope.hasMore = scope.topic.replyCount>endAt?true:false;
				var paramReply = {
					"snsTopicId":snsTopicId,
					"page" : 1,
					"countPerPage" : endAt,
					"sortOption": 1
				}
				snsService.getReplies(paramReply).then(function(replydata){
					if(replydata.status ==0){				
						scope.topic.partReplies = replydata.data.replies;
					}
				})

			}
		}
	}
});


app.directive('pullableView', function($rootScope, $timeout, snsService){
	return {
		restrict: "A",
		scope : {
            topics: '=topics'
        },
		link: function(scope, element, attrs){
			scope.isTapping = false;
			var el = element;
			var wrapper = angular.element(document.querySelector(".container.main-content"));
			var wrapperH = wrapper[0].offsetHeight;
			var startedTop = 30, movedTop;
			var originalY = 0;
			var newY = 0;
			scope.$parent.refreshHeight = 0;
			el.on("touchstart", touchStartHandler);
			el.on("touchend", touchEndHandler);
			function touchStartHandler(e){
				//e.preventDefault();
				//if(scope.topics.length>=10){
					scope.$parent.isTapping = true;
				//}
				startedTop = wrapper[0].scrollTop;
				//console.log("touch start: " + scope.isTapping)
				el.on('touchmove',touchMoveHandler);
				if(wrapper[0].scrollTop + wrapperH >= wrapper[0].scrollHeight-10){
					scope.$parent.showMore = true;
				}
				originalY = (e.targetTouches && e.targetTouches.length)? e.targetTouches[0].clientY:0;
				scope.$apply();
			}
			function touchMoveHandler(e){		
				e.stopPropagation();
				//console.log("top: " + wrapper[0].scrollTop + "; scroll: " + wrapper[0].scrollHeight + "; height: "+ wrapperH)
				//console.log((wrapper[0].scrollTop + wrapperH) + " vs " +  (wrapper[0].scrollHeight-50))
				// pull up to show more
				
				if(wrapper[0].scrollTop + wrapperH >= wrapper[0].scrollHeight-10){
					scope.$parent.showMore = true;

					//console.log(" show more.... ")
				}else{
					scope.$parent.showMore = false;
				}
			
				// pull down to refresh

				newY = (e.targetTouches && e.changedTouches.length)? e.changedTouches[0].clientY:0;
				if(startedTop == 0 && originalY<newY-10){
					scope.$parent.showRefresh = true;
					scope.$parent.refreshHeight = newY - originalY>50?50:(newY - originalY);
					scope.$parent.$apply();
				}else{
					scope.$parent.showRefresh = false;
				}

			}
			function touchEndHandler(e){
				var touch = e.touches[0];
				el.off('touchmove', touchMoveHandler);
				scope.$parent.isTapping = false;
				newY = (e.targetTouches && e.changedTouches.length)? e.changedTouches[0].clientY:0;

				if(Math.abs(originalY-newY)<=10)
					return;
				if( scope.topics.length>=10){
					if(scope.$parent.showMore){
						$rootScope.$emit("LOAD_MORE_TITLES_EVENT");
					}
				}
				if(scope.$parent.noMorePage){
					scope.$parent.showMore = false;
				}
				if(scope.$parent.showRefresh){
					$rootScope.$emit("REFRESH_TITLES_EVENT");
					scope.$parent.showRefresh = false;
					wrapper[0].scrollTop = 0;
				}
				scope.$parent.refreshHeight = 0;
				scope.$parent.$apply();
				
			};

		}
	}
});

// iOS don't support update file in UIWebView
app.directive('fileUploader', function(snsService) {
    return {
        restrict: 'A',
        transclude: true,
        link: function($scope, $element) {
            var fileInput = $element;
			$scope.isUploadSuccess = false;
            fileInput.bind("change",function(e) {
                $scope.isPending = true;
                if(e.target.files.length){
					snsService.updateFile(e.target.files[0]).then(function(data){
						if(data.status==0){
							$scope.imgUrl = data.data.imgUrl;
							$scope.isPending = false;
							$scope.isUploadSuccess = true;
						}
					});
				}
            });
        }
    }
});

app.directive('mcProvince', function(snsService) {
    return {
        restrict: 'E',
		replace: true,
		templateUrl: "views/tmpl_province.html",
		scope : {
            provinces : '=provinces',
            cities : '=cities'
        },
        link: function($scope, $element) {
           
        }
    }
});

app.directive('mcProvinceSelector', function($rootScope, $timeout, snsService) {
    return {
        restrict: 'A',
        link: function($scope, $element) {
        	Log.log("------ init province");
			$timeout(function(){
				var provinceScroll = new DiaboSlider($element[0]);
				Log.log("province selector");
				provinceScroll.bind("selectedUpdate", function(e){	
					Log.log("========province selected========")
					$rootScope.hasCities = false;
					var pid = e.selectedElement.getAttribute("data-province-id")*1;
					$rootScope.selectedRegion = {provinceId: pid, provinceName: $rootScope.provinces[e.selectedIndex].name};
					$rootScope.cities = $rootScope.provinces[e.selectedIndex].cities;
					$rootScope.hasCities = true;
					$rootScope.$apply();
				
				});
				
				
			},1);
        }
    }
});


app.directive('mcCitySelector', function($rootScope,$timeout,$location,snsService) {
    return {
        restrict: 'A',
		scope : {
            schools : '=schools'
        },
        link: function($scope, $element) {
			if($rootScope.citiesWatcher){
				$rootScope.citiesWatcher();
			}
			Log.log("------ init city");
			var cityScroll = new DiaboSlider($element[0]);
			//console.log(cityScroll.wrapper)
			var cityIndex = 0;
			cityScroll.bind("selectedUpdate", function(e){	
				cityIndex = e.selectedIndex;
				Log.log("========city selected========" + e.selectedIndex)
				var cid = e.selectedElement.getAttribute("data-city-id")*1;
				$rootScope.selectedRegion.cityId = cid;
				$rootScope.selectedRegion.cityName = $rootScope.cities[cityIndex].name;
				var backUrl=getParameterFromUrl("backUrl");
				var parentBackUrl = backUrl.split('|');
				$timeout(function(){
					$location.url(parentBackUrl[0]).search({backUrl:parentBackUrl[1]});
				},1);
			});		
			$rootScope.citiesWatcher = $rootScope.$watch("cities", function( newVal ) { 
				//console.log("$rootScope.provinces[provinceIndex]", $rootScope.cities);
				if(!newVal) return;
				//console.log(cityScroll.wrapper);
				$timeout(function(){
					cityScroll.refresh();
				},2);
			});
        }
    }
});



app.directive('mcSchoolSelector', function($rootScope,$timeout,$location,snsService) {
    return {
        restrict: 'A',
        link: function($scope, $element) {
			
			var schoolScroll = new DiaboSlider($element[0]);
			Log.log("----- init school")
			schoolScroll.bind("selectedUpdate", function(e){	
				var sid = e.selectedElement.getAttribute("data-school-id")*1;
				$rootScope.selectedRegion.drivingSchoolId = sid;
				
				$rootScope.selectedRegion.schoolName = $rootScope.schools[e.selectedIndex].schoolName;
				$timeout(function(){
					$location.path("/enroll");
				},1);
			});		
			$rootScope.$watch("schools", function( newVal ) { 
				//console.log("$rootScope.provinces[provinceIndex]", $rootScope.cities);
				if(!newVal) return;
				//console.log(cityScroll.wrapper);
				setTimeout(function(){
					schoolScroll.refresh();
				},2);
			});
        }
    }
});

app.directive('swipeView', function( $rootScope ){
	return {
		restrict: "E",		
		replace: true,
		templateUrl: 'views/tmpl_swipe_view.html',
		content:"=content",
		link: function(scope, element, attrs){
			var sw = (document.body.clientWidth || window.screen.width);
			var sh = element[0].offsetHeight;
			var myScroll;
			scope.$watch("content", function(newVal){
				if(!newVal)
					return;
				scope.num = scope.content.images.length;
				scope.curIndex = newVal.index;
				scope.scrollerWidth = scope.num * sw;
				scope.slideWidth = sw;
				scope.sliderHeight = sh;
				scope.indicatorWidth = scope.num * 20 -10;
				scope.dots = [0,1,2];
				
				setTimeout(function(){
					myScroll = new IScroll(document.querySelector('.slider-view'), {
						scrollX: true,
						scrollY: false,
						momentum: false,
						snap: true,
						click:true,
						snapSpeed: 400,
						keyBindings: true,				
						indicators: {
							el: document.querySelector('.indicator'),
							resize: false
						}
					});	
					myScroll.scrollBy(-scope.curIndex * sw, 0,0);		
					myScroll.on("scrollEnd", function(e){
						scope.curIndex = parseInt(Math.abs(myScroll.x / myScroll.wrapperWidth));
						scope.$apply();
					});
				},100);
			})
			
			scope.close = function($event){;
				$event.stopPropagation();
				$rootScope.$emit("HIDE_IMAGE_SLIDER_EVENT");
				return;
			}
		}
	}
});








app.directive("datePicker", function(){
	return {
		restrict: "EA",
		replace: true,
		template: '<input type="text" placeholder="{{placeHolder}}" required="required"/>',
		link: function(scope, element, attrs){
			scope.placeHolder = attrs.placeholder || "";
			element.bind("touchend", function(){
				element.attr("type","date");
				element[0].focus();
			});
			element.bind("blur", function(){
				element.attr("type","text");
			});
		}
	}
})






app.directive('bindHtmlUnsafe', function( $compile ) {
    return function( $scope, $element, $attrs ) {
        var compile = function( newHTML ) {
            newHTML = $compile(newHTML)($scope);
            $element.html('').append(newHTML); 
        };
        var htmlName = $attrs.bindHtmlUnsafe; 
        $scope.$watch(htmlName, function( newHTML ) { 
            if(!newHTML) return;
            compile(newHTML); 
        });
    };
});


app.directive('focusOn', function() {
	return function(scope, elem, attr) {
		scope.$on('focusOn', function(e, name) {
			if(name === attr.focusOn) {
				elem[0].focus();
				console.log("set focus")
			}
		});
	};
});

app.directive('verticalAlign', function () {       
    return {
        link: function(scope, element, attrs) {   
			Log.log("====== img");
			var sw = (document.body.clientWidth || window.screen.width);
			var sh = element.parent()[0].offsetHeight;
			element.parent().addClass("loading");
			element.css("display", "none");
            element.bind("load" , function(e){ 

                // success, "onload" catched
				var nw = sw;
				var nh = this.naturalHeight/this.naturalWidth * nw;
				
				var top;
				if(attrs.verticalAlign == "top")
					top = 0;
				else if(attrs.verticalAlign == "bottom")
					top = (sh - nh);
				else if(attrs.verticalAlign == "middle" || !attrs.verticalAlign)
					top = (sh - nh)/2;
				Log.log(nw + ", " + nh + ", screen: " + sw + ", " + sh + "; top: " + top)
				element.css({
					"marginTop": top + "px",
					"width": nw + "px",
					"display": ""
				});
				
				/*
                if(this.naturalHeight > this.naturalWidth){
                    this.className = "vertical";
                }
				*/
            });
        }
    }
});

app.directive('logComponent', ["$window", function($window){
	return {
		restrict: "E",
		replace: true,
		templateUrl: "views/tmpl_log_component.html",
		link: function(scope, element, attrs){
			var Log = {
				log: function(){
					var str = "";
					var toString = function(arg){
						if(typeof(arg) == "string"){
							return arg;
						}
						else if(typeof(arg) == "object"){
							return JSON.stringify(arg);
						} 
					}
					if(arguments.length == 1){
						str = toString(arguments[0]);
					}
					else if(arguments.length > 1 ){
						for(var i=0;i<arguments.length;i++){
							str += toString(arguments[i]) + "<br/>";
						}
					}
					if(typeof(arguments[arguments.length-1])=="boolean"){
						if(arguments[arguments.length-1] == false){

							document.querySelector(".txtLog").innerHTML = str;
						}else{
							document.querySelector(".txtLog").innerHTML = (document.querySelector(".txtLog").innerHTML + "<br/>" + str);
						}
					}else{
						document.querySelector(".txtLog").innerHTML = (document.querySelector(".txtLog").innerHTML + "</br>" + str);
					}
				},
				clear: function(){
					document.querySelector(".txtLog").innerHTML = "";
				}
			};
			if(useLog){
				window.Log = Log;
			}
			else{
				element[0].style.display = "none";
				window.Log = {
					log: function(){
						return;
					}
				}
			}
			scope.showLog = function(){
				document.querySelector(".logComponent").style.display = "";
			};
			scope.hideLog = function(){
				document.querySelector(".logComponent").style.display = "none";
			};
			scope.clearLog = function(){
				Log.clear();
			};
		}
	}
}]);

app.directive('myFooter', function () {
	return {
		restrict:'E',
		replace:true,
		templateUrl:'views/tmpl_my_footer.html'
	};
});
